package com.shenhaofeng.app.component.dialog;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;

import com.shenhaofeng.app.R;


/**
 * Created by Administrator on 2016/8/1.
 */
public class LoadingDialogFragment extends DialogFragment {

    /**
     * loading Tag标签
     */
    public static final String TAG = LoadingDialogFragment.class.getName();



    public LoadingDialogFragment() {
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.dialog_loading, container, false);
    }





    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(STYLE_NO_TITLE, 0);
    }





    @Override
    public void onStart() {
        super.onStart();
        Window window = getDialog().getWindow();
        window.setLayout(WindowManager.LayoutParams.WRAP_CONTENT, getDialog().getWindow().getAttributes().height);
        window.setBackgroundDrawableResource(android.R.color.transparent);
        window.setGravity(Gravity.CENTER);
    }





    /**
     * 显示每个Activity唯一的loading
     *
     * @param fragmentManager
     * @param tag
     */
    public static void showLoading(FragmentManager fragmentManager, String tag) {
        Fragment fragment = fragmentManager.findFragmentByTag(tag);
        if (fragment != null && fragment instanceof LoadingDialogFragment) {
            ((LoadingDialogFragment) fragment).dismiss();
        }
        LoadingDialogFragment loadingDialogFragment = new LoadingDialogFragment();
        loadingDialogFragment.show(fragmentManager, tag);

    }





    /**
     * 显示每个Activity唯一的loading
     *
     * @param fragmentManager
     */
    public static void showLoading(FragmentManager fragmentManager) {
        showLoading(fragmentManager, TAG);
    }





    /**
     * 销毁loading
     * @param fragmentManager
     * @param tag
     */
    public static void dismiss(FragmentManager fragmentManager, String tag) {
        Fragment fragment = fragmentManager.findFragmentByTag(tag);
        if (fragment != null && fragment instanceof LoadingDialogFragment) {
            ((LoadingDialogFragment) fragment).dismiss();
        }
    }





    /**
     *  销毁loading
     * @param fragmentManager
     */
    public static void dismiss(FragmentManager fragmentManager) {
        dismiss(fragmentManager, TAG);
    }
}
